package org.example.school.business;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.school.common.Context;
import org.example.school.entity.AttendanceRecords;
import org.example.school.entity.EventRegistrations;
import org.example.school.entity.Leave;
import org.example.school.entity.SchoolEvents;
import org.example.school.entity.Students;
import org.example.school.model.dto.LeaveDTO;
import org.example.school.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

@Component
public class StudentInfo {
    
    @Autowired
    private ISchoolEventsService schoolEventsService;
    
    @Autowired
    private IEventRegistrationsService eventRegistrationsService;
    
    @Autowired
    private IStudentsService studentsService;
    
    @Autowired
    private IAttendanceRecordsService attendanceRecordsService;
    
    @Autowired
    private IClassesService classesService;
    
    @Autowired
    private ILeaveService leaveService;
    
    /**
     * 获取所有活动列表
     * @return 活动列表
     */
    public List<SchoolEvents> getAllEvents() {
        return schoolEventsService.list(
            new QueryWrapper<SchoolEvents>().orderByDesc("created_at")
        );
    }
    
    /**
     * 获取当前学生的报名列表
     * @return 报名列表
     */
    public List<EventRegistrations> getMyRegistrations() {
        Long userId = Context.getId();
        return eventRegistrationsService.list(
            new QueryWrapper<EventRegistrations>().eq("user_id", userId)
        );
    }
    
    /**
     * 为学生报名活动
     * @param eventId 活动ID
     * @return 报名结果
     */
    public String registerEvent(Long eventId) {
        Long userId = Context.getId();
        
        // 检查是否已经报名
        EventRegistrations existingRegistration = eventRegistrationsService.getOne(
            new QueryWrapper<EventRegistrations>()
                .eq("event_id", eventId)
                .eq("user_id", userId)
        );
        
        if (existingRegistration != null) {
            throw new RuntimeException("您已经报名过此活动");
        }
        
        // 获取学生信息
        Students student = studentsService.lambdaQuery()
                .eq(Students::getUserId, userId)
                .one();
        
        if (student == null) {
            throw new RuntimeException("学生信息不存在");
        }
        
        // 创建报名记录
        EventRegistrations registration = new EventRegistrations();
        registration.setEventId(eventId);
        registration.setUserId(userId);
        registration.setRegisteredAt(LocalDateTime.now());
        registration.setUserType("2"); // 学生类型
        registration.setFullName(student.getFullName()); // 学生真实姓名
        eventRegistrationsService.save(registration);
        
        return "报名成功";
    }
    
    /**
     * 取消报名
     * @param registrationId 报名ID
     * @return 取消结果
     */
    public String cancelRegistration(Long registrationId) {
        Long userId = Context.getId();
        
        // 检查报名记录是否存在且属于当前用户
        EventRegistrations registration = eventRegistrationsService.getOne(
            new QueryWrapper<EventRegistrations>()
                .eq("id", registrationId)
                .eq("user_id", userId)
        );
        
        if (registration == null) {
            throw new RuntimeException("报名记录不存在或无权限操作");
        }
        
        // 删除报名记录
        eventRegistrationsService.removeById(registrationId);
        return "取消报名成功";
    }
    
    /**
     * 学生早上签到
     * @param studentNumber 学号
     * @return 签到结果
     */
    public String clockInMorning(String studentNumber) {
        try {
            // 检查学生是否存在
            Students student = studentsService.lambdaQuery().eq(Students::getStudentNumber, studentNumber).one();
            Long studentId = student.getId();
            if (student == null) {
                throw new RuntimeException("学生不存在");
            }

            // 获取当前时间
            LocalDateTime now = LocalDateTime.now();
            LocalTime currentTime = now.toLocalTime();
            LocalDate currentDate = now.toLocalDate();

            // 检查当天是否已经请假
            AttendanceRecords leaveRecord = attendanceRecordsService.getOne(
                    new QueryWrapper<AttendanceRecords>()
                            .eq("student_id", studentId)
                            .eq("record_date", currentDate)
                            .eq("status", "4") // 请假状态
            );

            if (leaveRecord != null) {
                throw new RuntimeException("该学生已请假，无需签到");
            }

            // 检查是否已经打过卡（包括上午和下午）
            AttendanceRecords existingRecord = attendanceRecordsService.getOne(
                    new QueryWrapper<AttendanceRecords>()
                            .eq("student_id", studentId)
                            .eq("record_date", currentDate)
                            .ne("status", "4") // 排除请假记录
            );

            if (existingRecord != null) {
                throw new RuntimeException("今天已经签到过，请勿重复签到");
            }

            // 创建新的签到记录
            AttendanceRecords record = new AttendanceRecords();
            record.setStudentId(studentId);
            record.setRecordDate(currentDate);
            record.setRecordedAt(now);
            // 从上下文中获取教师ID，如果获取不到则默认为1L
            Long teacherId = classesService.getById(student.getClassId()).getHeadTeacherId();
            record.setRecordedByTeacherId(teacherId != null ? teacherId : 1L);

            // 根据时间判断状态
            if (currentTime.isBefore(LocalTime.of(8, 0))) {
                // 8点前签到，正常
                record.setStatus("1"); // 出勤
            } else {
                // 8点后签到，迟到
                record.setStatus("3"); // 迟到
            }

            attendanceRecordsService.save(record);
            return "上午签到成功";
        } catch (Exception e) {
            throw new RuntimeException("签到失败: " + e.getMessage());
        }
    }

    /**
     * 学生下午签退
     * @param studentNumber 学号
     * @return 签退结果
     */
    public String clockOutAfternoon(String studentNumber) {
        try {
            // 检查学生是否存在
            Students student = studentsService.lambdaQuery().eq(Students::getStudentNumber, studentNumber).one();
            Long studentId = student.getId();
            if (student == null) {
                throw new RuntimeException("学生不存在");
            }

            // 获取当前时间
            LocalDateTime now = LocalDateTime.now();
            LocalTime currentTime = now.toLocalTime();
            LocalDate currentDate = now.toLocalDate();

            // 检查当天是否已经请假
            AttendanceRecords leaveRecord = attendanceRecordsService.getOne(
                    new QueryWrapper<AttendanceRecords>()
                            .eq("student_id", studentId)
                            .eq("record_date", currentDate)
                            .eq("status", "4") // 请假状态
            );

            if (leaveRecord != null) {
                throw new RuntimeException("该学生已请假，无需签退");
            }

            // 检查是否已经签到
            AttendanceRecords morningRecord = attendanceRecordsService.getOne(
                    new QueryWrapper<AttendanceRecords>()
                            .eq("student_id", studentId)
                            .eq("record_date", currentDate)
                            .ne("status", "4") // 排除请假记录
            );

            if (morningRecord == null) {
                throw new RuntimeException("请先完成上午签到");
            }

            // 更新签退信息
            if (currentTime.isBefore(LocalTime.of(18, 0))) {
                // 18点前签退，早退
                morningRecord.setRemarks("早退");
                morningRecord.setStatus("5"); // 早退状态
                attendanceRecordsService.updateById(morningRecord);
                return "下午签退成功，状态：早退";
            } else {
                // 18点后签退，正常
                return "下午签退成功，状态：正常";
            }
        } catch (Exception e) {
            throw new RuntimeException("签退失败: " + e.getMessage());
        }
    }
    
    /**
     * 学生请假申请
     * @param leaveDTO 请假信息
     * @return 请假结果
     */
    public String leave(LeaveDTO leaveDTO) {
        try {
            Students student = studentsService.lambdaQuery().eq(Students::getStudentNumber, leaveDTO.getStudentNumber()).one();
            String studentNumber = student.getStudentNumber();
            Long teacherId = classesService.getById(student.getClassId()).getHeadTeacherId();
            // 检查学生是否存在
            if (student == null) {
                throw new RuntimeException("学生不存在");
            }

            Leave leave = new Leave();
            leave.setStudentNumber(studentNumber);
            leave.setStartDate(leaveDTO.getStartDate());
            leave.setEndDate(leaveDTO.getEndDate());
            leave.setStatus("1"); // 等待审批
            leave.setRemarks(leaveDTO.getRemarks());
            leave.setTeacherId(teacherId);
            leave.setCreateTime(LocalDate.now());
            leave.setUpdateTime(LocalDate.now());
            leave.setStudentName(student.getFullName());
            leaveService.save(leave);

            return "请假申请提交成功";
        } catch (Exception e) {
            throw new RuntimeException("请假失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取学生请假记录
     * @param studentNumber 学号
     * @return 请假记录列表
     */
    public List<Leave> getLeaveStatus(String studentNumber) {
        return leaveService.lambdaQuery().eq(Leave::getStudentNumber, studentNumber).list();
    }
    
    /**
     * 撤销请假申请
     * @param leaveId 请假ID
     * @return 撤销结果
     */
    public String cancelLeave(long leaveId) {
        Leave leave = leaveService.getById(leaveId);
        leave.setStatus("2"); // 撤销审批
        leave.setUpdateTime(LocalDate.now());
        boolean result = leaveService.updateById(leave);
        if (result) {
            return "撤销成功";
        } else {
            throw new RuntimeException("撤销失败");
        }
    }
    
    /**
     * 查询学生考勤记录
     * @param studentNumber 学号
     * @return 考勤记录列表
     */
    public List<AttendanceRecords> getAttendRecords(String studentNumber) {
        try {
            // 检查学生是否存在
            Students student = studentsService.lambdaQuery().eq(Students::getStudentNumber, studentNumber).one();
            if (student == null) {
                throw new RuntimeException("学生不存在");
            }

            // 查询该学生的所有考勤记录
            return attendanceRecordsService.list(
                    new QueryWrapper<AttendanceRecords>()
                            .eq("student_id", student.getId())
                            .orderByDesc("record_date") // 按日期倒序排列
            );
        } catch (Exception e) {
            throw new RuntimeException("查询失败: " + e.getMessage());
        }
    }
}